package com.library.controller;

import com.library.entity.Admin;
import com.library.entity.Book;
import com.library.entity.Reader;
import com.library.service.BookService;
import com.library.service.ReaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private BookService bookService;

    @Autowired
    private ReaderService readerService;

    @GetMapping("/login")
    public String loginForm() {
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       HttpSession session,
                       Model model) {
        // 管理员登录验证（这里简化处理，实际应该从数据库查询）
        if ("admin".equals(username) && "admin123".equals(password)) {
            Admin admin = new Admin();
            admin.setUsername(username);
            admin.setPassword(password);
            session.setAttribute("admin", admin);
            return "redirect:/admin/dashboard";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "admin/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("admin");
        return "redirect:/admin/login";
    }

    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        if (session.getAttribute("admin") == null) {
            return "redirect:/admin/login";
        }
        return "admin/dashboard";
    }

    @GetMapping("/books")
    public String manageBooks(Model model) {
        model.addAttribute("books", bookService.getAllBooks());
        return "admin/books";
    }

    @GetMapping("/readers")
    public String manageReaders(Model model) {
        model.addAttribute("readers", readerService.getAllReaders());
        return "admin/readers";
    }

    @GetMapping("/reader/edit/{id}")
    public String editReaderForm(@PathVariable Integer id, Model model) {
        Reader reader = readerService.getReaderById(id);
        model.addAttribute("reader", reader);
        return "admin/editReader";
    }

    @PostMapping("/reader/update")
    public String updateReader(@ModelAttribute Reader reader) {
        readerService.updateReader(reader);
        return "redirect:/admin/readers";
    }

    @PostMapping("/reader/delete/{id}")
    public String deleteReader(@PathVariable Integer id) {
        readerService.deleteReader(id);
        return "redirect:/admin/readers";
    }
}